package com.grablist.feihu.grablist.ui.actviity.login;

import android.Manifest;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.grablist.feihu.grablist.R;
import com.grablist.feihu.grablist.base.BaseActivity;
import com.grablist.feihu.grablist.bean.CityInfo;
import com.grablist.feihu.grablist.bean.MeituanHeaderBean;
import com.grablist.feihu.grablist.comm.Constants;
import com.grablist.feihu.grablist.comm.MyType;
import com.grablist.feihu.grablist.event.CityEvent;
import com.grablist.feihu.grablist.event.CloseActEvent;
import com.grablist.feihu.grablist.event.DelectEvent;
import com.grablist.feihu.grablist.event.NetErrorEvent;
import com.grablist.feihu.grablist.event.SelectCityEvent;
import com.grablist.feihu.grablist.ui.actviity.login.biz.CityBiz;
import com.grablist.feihu.grablist.ui.actviity.login.component.DaggerCityComponent;
import com.grablist.feihu.grablist.ui.actviity.login.contract.CityContract;
import com.grablist.feihu.grablist.ui.actviity.login.module.CityModule;
import com.grablist.feihu.grablist.ui.actviity.login.presenter.CityPresenter;
import com.grablist.feihu.grablist.ui.adapter.CityAdapter;
import com.grablist.feihu.grablist.ui.adapter.CityHeaderAdapter;
import com.grablist.feihu.grablist.util.PermissionUtils;
import com.jakewharton.rxbinding.view.RxView;
import com.superrecycleview.superlibrary.callback.SuspensionDecoration;
import com.superrecycleview.superlibrary.sidebar.bean.BaseIndexPinyinBean;
import com.superrecycleview.superlibrary.sidebar.widget.SuperSideBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.Bind;
import rx.functions.Action1;

/**
 * Created by admin on 2017/12/7.
 */

public class SelectCityAct extends BaseActivity implements CityContract.View {


    @Inject
    CityPresenter presenter;
    @Inject
    CityBiz biz;
    @Bind(R.id.select_city_recycle_view)
    RecyclerView recycleView;
    @Bind(R.id.select_city_side_bar)
    SuperSideBar sideBar;//右侧边栏导航区域
    @Bind(R.id.select_city_hint)
    TextView hint;//显示指示器DialogText
    @Bind(R.id.needsx)
    TextView needsx;

    String selectCityInfo = "";
    List<String> recentCitys = new ArrayList<>();
    CityAdapter cityAdapter;
    CityHeaderAdapter headerAdapter;


    // 设置给InexBar、ItemDecoration的完整数据集
    private List<BaseIndexPinyinBean> mSourceDatas = new ArrayList<>();
    // 头部数据源
    private List<MeituanHeaderBean> mHeaderDatas = new ArrayList<>();

    private SuspensionDecoration mDecoration;
    LinearLayoutManager layoutManager;

    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    //申请权限
    private final String[] PERMISSIONS = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
    };


    // 打开相机定位请求Code，多个权限请求Code
    private final int REQUEST_CODE_PERMISSIONS = 2;

    @Override
    protected void setRoot() {
        setTitleBar("#FFFFFFFF");
        setContentView(R.layout.activity_city_info);

    }

    @Override
    protected void setup() {
        DaggerCityComponent.builder().cityModule(new CityModule(this)).build().inject(this);
        setStateText();
        setToolBar("城市", "");
        needsx.setText("确定");
        presenter.setBiz(biz);
    }


    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            initLocation();
            startLocation();
        } else {
            requestMorePermissions();
        }
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(layoutManager);
        presenter.getData();

        RxView.clicks(needsx)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        EventBus.getDefault().post(new SelectCityEvent(selectCityInfo));
                        finishAct();
                    }
                });


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCloseActEvent(CloseActEvent event) {
        if (event.getType() == MyType.city) {
            finishAct();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void  onCityEvent(CityEvent info) {
        if(!selectCityInfo.contains(info.getCity())){
            if(recentCitys.size()>=5){
                showMsg("您已选满5个城市，无法再选");
            }else{
                StringBuffer   testStrBuff=new StringBuffer(selectCityInfo);
                testStrBuff.append(info.getCity()+",");
                selectCityInfo=testStrBuff.toString();
                recentCitys.add(info.getCity());
                headerAdapter.notifyDataSetChanged();
            }

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void  onDelectEvent(DelectEvent info) {
        if(selectCityInfo.contains(info.getCity())){
            selectCityInfo=selectCityInfo.replace(info.getCity()+",","");
            for (String stu : recentCitys) {
                if (stu.equals(info.getCity())) {
                    recentCitys.remove(stu);
                    break;
                }
            }
            headerAdapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    /***
     * Stop location service
     */
    @Override
    protected void onStop() {
        stopLocation();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        biz.onDestory();
        stopLocation();

    }


    @Override
    public void updateImages(List<CityInfo> citys, List<String> hotCity) {
//        if (cityAdapter == null) {
//            cityAdapter = new CityAdapter(this, citys);
//        } else {
//            cityAdapter.notifyDataSetChanged();
//        }
//        //创建头适配器
//        headerAdapter = new CityHeaderAdapter(cityAdapter, this);
//        //点位标签
//
//        List<String> locationCity = new ArrayList<>();
//        mHeaderDatas.add(new MeituanHeaderBean(locationCity, "定位城市", "定位"));
//        //最近标签
//        List<String> recentCitysLable = new ArrayList<>();
//        mHeaderDatas.add(new MeituanHeaderBean(recentCitysLable, "最多选5个(长按删除)", ""));
//        //热门标签
//        List<String> hotCitysLable = new ArrayList<>();
//        mHeaderDatas.add(new MeituanHeaderBean(hotCitysLable, "热门城市", "热门"));
//        mSourceDatas.addAll(mHeaderDatas);
//        headerAdapter.setHeaderView(0, R.layout.view_city_header_layout, mHeaderDatas.get(0));
//        headerAdapter.setHeaderView(1, R.layout.view_city_header_layout, mHeaderDatas.get(1));
//        headerAdapter.setHeaderView(2, R.layout.view_city_header_layout, mHeaderDatas.get(2));
//        headerAdapter.notifyDataSetChanged();
//        recycleView.setAdapter(headerAdapter);
//        mDecoration = new SuspensionDecoration(this, citys)
//                .setmTitleHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 35,
//                        getResources().getDisplayMetrics()))
//                .setColorTitleBg(0xffefefef)
//                .setTitleFontSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16,
//                        getResources().getDisplayMetrics()))
//                .setColorTitleFont(
//                        SelectCityAct.this.getResources().getColor(android.R.color.black))
//                .setHeaderViewCount(headerAdapter.getHeaderViewCount() - mHeaderDatas.size());
//        recycleView.addItemDecoration(mDecoration);// 添加字母悬浮利用添加分割线的方式
//        recycleView.addItemDecoration(
//                SuperDivider.newBitmapDivider().setStartSkipCount(1).setEndSkipCount(0));
//        sideBar.setmPressedShowTextView(hint)// 设置滑动的字母A,B,C
//                .setNeedRealIndex(true)// 设置需要真实的索引
//                .setmLayoutManager(layoutManager);// 设置RecyclerView的LayoutManager
//
//        MeituanHeaderBean header1 = mHeaderDatas.get(0);
//        header1.getCityList().clear();
//        if (Constants.location != null) {
//            header1.getCityList().add(Constants.location.getCity());
//        } else {
//            header1.getCityList().add("未知");
//        }
//
//        MeituanHeaderBean header2 = mHeaderDatas.get(1);
//        header2.setCityList(recentCitys);
//        MeituanHeaderBean header3 = mHeaderDatas.get(2);
//        header3.setCityList(hotCity);
//        mSourceDatas.addAll(citys);
//        //设置右侧的
//        sideBar.getDataHelper().sortSourceDatas(citys);
//        sideBar.setSourceDatas(mSourceDatas);// 设置数据
//        mDecoration.setDatas(mSourceDatas);

    }


    // 自定义申请多个权限
    private void requestMorePermissions() {
        PermissionUtils.checkMorePermissions(SelectCityAct.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
            @Override
            public void onHasPermission() {
                initLocation();
                startLocation();
            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {
//                showExplainDialog(permission, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        PermissionUtils.requestMorePermissions(SelectCityAct.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
//                    }
//                });
            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                PermissionUtils.requestMorePermissions(SelectCityAct.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
            }
        });
    }


    /**
     * 解释权限的dialog
     */
    private void showExplainDialog(String[] permission, DialogInterface.OnClickListener onClickListener) {
        new AlertDialog.Builder(SelectCityAct.this)
                .setTitle("申请权限")
                .setMessage("我们需要" + Arrays.toString(permission) + "权限")
                .setPositiveButton("确定", onClickListener)
                .show();
    }

    /**
     * 显示前往应用设置Dialog
     */
    private void showToAppSettingDialog() {
        new AlertDialog.Builder(SelectCityAct.this)
                .setTitle("需要权限")
                .setMessage("我们需要相关权限，才能实现功能，点击前往，将转到应用的设置界面，请开启应用的相关权限。")
                .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PermissionUtils.toAppSetting(SelectCityAct.this);
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {

            case REQUEST_CODE_PERMISSIONS:
                PermissionUtils.onRequestMorePermissionsResult(SelectCityAct.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
                    @Override
                    public void onHasPermission() {
                        initLocation();
                        startLocation();
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDown(String... permission) {
                        Toast.makeText(SelectCityAct.this, "我们需要" + Arrays.toString(permission) + "权限", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
//                        Toast.makeText(SelectCityAct.this, "我们需要" + Arrays.toString(permission) + "权限", Toast.LENGTH_SHORT).show();
//                        showToAppSettingDialog();
                    }
                });
        }
    }

    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(SelectCityAct.this);
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }


    /**
     * 默认的定位参数
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
//        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    /**
     * 开始定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void startLocation() {
        //根据控件的选择，重新设置定位参数
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {
                Constants.location = location;

            }

        }
    };

}
